package com.power.filter;

import com.alibaba.fastjson.JSONObject;
import com.power.constant.AuthConstants;
import com.power.model.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Description Token转换过滤器
 * @Author dingchunlin
 * @Date 2024/07/12 14:46
 * @Version 1.0.0
 */
@Component
public class TokenTranslationFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * token转换器
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 这里可以做一些Token转换的操作
        String authorizationValue = request.getHeader(AuthConstants.AUTHORIZATION);
        // 判断是否有值
        if (StringUtils.hasText(authorizationValue)){
            //获取token
            String token = authorizationValue.replace(AuthConstants.BEARER, "");
            //从redis中获取用户信息
            if (StringUtils.hasText(token)){

                // 从redis中获取过期时间,解决token续签问题
                Long expireTime = stringRedisTemplate.getExpire(AuthConstants.LOGIN_TOKEN_PREFIX + token);
                // 判断是否超过系统指定的阈值
                if (expireTime < AuthConstants.TOKEN_EXPIRE_THRESHOLD_TIME){
                    // 续签token
                    stringRedisTemplate.expire(AuthConstants.LOGIN_TOKEN_PREFIX + token, AuthConstants.TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
                }

                String userInfo = stringRedisTemplate.opsForValue().get(AuthConstants.LOGIN_TOKEN_PREFIX + token);
                //将json字符串转换成对象
                SecurityUser securityUser = JSONObject.parseObject(userInfo, SecurityUser.class);
                //处理权限
                Set<SimpleGrantedAuthority> collect = securityUser.getPerms().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
                //创建UsernamePasswordAuthenticationToken对象
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(securityUser, null, collect);

                //将认证对象放到当前模块上下文中
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        // 继续执行过滤器链
        filterChain.doFilter(request, response);
    }
}
